package com.mrjy.video.bo;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mrjy.common.entity.MessageInfo;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.entity.VideoVip;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.coursepackage.dao.ICoursePackageVipDao;
import com.mrjy.coursepackage.dto.CoursePackageVipDTO;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.video.dao.IVideoInfoDao;
import com.mrjy.video.dao.IVideoVipDao;
import com.mrjy.video.dto.VideoVipDTO;

@Service
public class VideoVipBo implements IVideoVipBo {
	
	@Resource
	private IVideoVipDao videoVipDao;
	@Resource
	private IMessageInfoDao messageInfoDao;
	@Resource
	private IUserInfoDao userInfoDao;
	@Resource
	private RedisPool redisPool;
	@Resource
	private ICoursePackageVipDao coursePackageVipDao;
    @Resource
    private IVideoInfoDao videoInfoDao;

    @Override
    public Object txInsert(VideoVip info) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = videoVipDao.insert(info);
		if (count > 0 ) {
			map.put("err_code", 0);
			map.put("err_msg", "插入成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "插入失败");
		}
		return map;
	}
	
	@Override
	public Object txCheckVideoVipExpired() {
		Map<String , Object> map = new HashMap<String, Object>();
		//1.先检查视频会员过期的记录，并将会员状态is_vip_status=1 改成 临时状态is_vip_status=2
		videoVipDao.updateCheckVideoVipExpired();
		//2.查出刚刚过期的记录，并添加提醒消息
		List<VideoVipDTO> list = videoVipDao.selectVideoVipExpired();
		if(null == list || list.size() == 0){
			map.put("err_code",1);
			map.put("err_msg", "没有过期课程包会员的数据");
		}else{
			for (VideoVipDTO info :list) {
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setContent("您购买的【"+ info.getVideoName() +"】已经到期，如想继续免费观看该视频");
				messageInfo.setTitle("已到期");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(info.getUserId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(7);
				messageInfo.setCostId(info.getVideoId()); //传视频的id
				messageInfo.setEndTime(info.getExpireTime());
				messageInfoDao.insert(messageInfo);
				
				//3.去除redis中用户相应的视频观看权限 
                String vids = redisPool.get(GlobalConstant.USER_VIDEO_VIP + info.getUserId()); //用户拥有观看权限的视频 ("8,17,23")
                //判断用户是否购买过包含该微课的课程包(coursepackageVip)
                CoursePackageVipDTO dto = new CoursePackageVipDTO();
                dto.setUserId(info.getUserId());
				dto.setVideoId(info.getVideoId());
				List<CoursePackageVipDTO> clist = coursePackageVipDao.isCoursePackageVipByVideoIdAndUserId(dto);
				if (clist == null || clist.size() == 0) {
					//如果没有购买过包含该微课的课程包,就直接去除该视频观看权限
					vids = vids.replace(info.getVideoId()+",", "");
				}
                redisPool.set(GlobalConstant.USER_VIDEO_VIP + info.getUserId(), vids);

            }
            //3.把临时状态为2的修改为0，变成非会员
            int count = videoVipDao.updateVideoVipExpired();
			map.put("err_code",0);
			map.put("err_msg", "已向"+  count  +"位用户发送会员到期提醒");
		}	
		return map;
	}
	
	@Override
	public Object checkVipVipWillExpire(int numDate) {
		Map<String,Object> map = new HashMap<String,Object>();
		//1.查询离会员过期还有numDate天的记录，并添加我的消息提醒
		List<VideoVipDTO> list= videoVipDao.selectVideoVipWillExpire(numDate);
		if(null == list || list.size() == 0){
			map.put("err_code",1);
			map.put("err_msg", "没有离过期还有" + numDate + "天的数据");
		}else{
			UserInfo ui = null;
			for (VideoVipDTO info : list) {
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setContent("您购买的微课【"+ info.getVideoName()  +"】即将到期（"+ info.getExpireTimeString() +" 到期）");
				messageInfo.setTitle("即将到期");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(info.getUserId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(7);
				messageInfo.setCostId(info.getVideoId());
				messageInfo.setEndTime(info.getExpireTime());
				messageInfoDao.insert(messageInfo);
				
			}
			map.put("err_code",0);
			map.put("err_msg", "已向"+  list.size()  +"位用户发送视频会员即将到期提醒");
		}
		return map;
	}

    @Override
    public Object selectHasPurchase(VideoVip videoVip) {
        Map<String, Object> map = new HashMap<String, Object>();

        if (videoVip.getUserId() == null) {
            map.put("err_code", 500);
            map.put("err_msg", "参数错误");
            return map;
        }

        List<VideoVipDTO> list = videoVipDao.selectHasPurchase(videoVip);

        for (VideoVipDTO info : list) {
            //视频
            if (info.getVideoId() != null) {
                VideoInfo vInfo = (VideoInfo) videoInfoDao.queryById(info.getVideoId());
                if (vInfo != null) {
                	info.setFreeFlag(vInfo.getFreeFlag());
                	info.setOriginalPrice(vInfo.getOriginalPrice());
                }

                if (vInfo.getFreeFlag() == 0) {
                    Boolean flag = RedisUtil.isVideoVip(videoVip.getUserId(), info.getVideoId());
                    if (flag) {
                    	info.setIsVipStatus(1 + "");
                    } else {
                    	info.setIsVipStatus(0 + "");
                    }
                } else {
                	info.setIsVipStatus(0 + "");
                }

                PolyInfo polyInfo = RedisUtil.cache(info.getVideoId() + "");
                info.setPolyInfo(polyInfo);
            }
        }

        if (list != null && list.size() > 0) {
            map.put("err_code", 200);
            map.put("rows", list);
            map.put("err_msg", "查询成功");
        } else {
            map.put("err_code", 201);
            map.put("rows", list);
            map.put("err_msg", "查询失败");
        }
        return map;
    }
}
